<template>
  <div class="add-edit-box" v-loading="loading">
    <div class="operate-btn">
      <div @click="back">返回</div>
      <div class="submit" @click="submitInfo">提交信息</div>
    </div>
    <div class="search-box">
      <el-row>
        <el-col :span="18" style="padding-left: 200px;">
          <el-input v-model="searchValue" placeholder="请输入企业名搜索" />
        </el-col>
        <el-col :span="6" style="padding-left: 10px">
          <el-button @click="cbeSync" type="danger">
            <el-icon style="vertical-align: middle">
              <RefreshLeft />
            </el-icon>
            <span style="vertical-align: middle"> CBE同步 </span>
          </el-button>
          <el-button @click="searchCustom" type="danger">
            <el-icon style="vertical-align: middle">
              <RefreshLeft />
            </el-icon>
            <span style="vertical-align: middle"> 企查查同步 </span>
          </el-button>
        </el-col>
      </el-row>
    </div>
    <el-form :model="customerForm" label-width="200">
      <el-row>
        <el-col :span="18">
          <el-form-item label="中文名">
            <el-input v-model="customerForm.zhName"></el-input>
          </el-form-item>
          <el-form-item label="中文简称">
            <el-input v-model="customerForm.zhShortName"></el-input>
          </el-form-item>
          <el-form-item label="英文名">
            <el-input v-model="customerForm.enName"></el-input>
          </el-form-item>
          <el-form-item label="logo" prop="logo">
            <ImageUpload v-model="customerForm.logo" :limit="1" />
          </el-form-item>
          <el-form-item label="客户类型">
            <el-radio-group v-model="customerForm.customType">
              <el-radio v-for="dict of custom_type" :label="dict.value" :key="dict.value">
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="展商类型">
            <el-radio-group v-model="customerForm.companyType">
              <el-radio v-for="dict of company_type" :label="dict.value" :key="dict.value">
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!--词条集合-->
          <template v-if="!loading">
            <el-form-item v-for="(item, index) of entryList" :key="index" :label="item.entryTitle">
              <el-input v-model="item.content" v-if="item.entryType === '1'"></el-input>

              <el-radio-group v-model="item.content" v-if="item.entryType === '2'">
                <el-radio v-for="sItem of item.optionVoList" :label="sItem.id" :key="sItem.id">
                  {{ sItem.optionName }}
                </el-radio>
              </el-radio-group>

              <el-checkbox-group v-model="item.content" v-if="item.entryType === '3'">
                <el-checkbox :label="sItem.id" v-for="(sItem, inx) of item.optionVoList" :key="inx">
                  {{ sItem.optionName }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </template>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import {defineComponent, onMounted, ref} from "vue";
import {saveCustom, updateCustom, queryQccInfo, synCbeInfo} from "@/api/customerInfo";
import {useRoute, useRouter} from "vue-router";
import ImageUpload from "@/components/ImageUpload/imageUpload.vue";
import {entryGetList} from "@/api/extendEntry";
import {RefreshLeft} from "@element-plus/icons-vue"
import dayjs from "dayjs";

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();
const props = defineProps({
  id: {
    type: String,
    default: ""
  },
  detail: {
    type: Object,
    default: () => {
    }
  }
});
const emit = defineEmits(["back", 'update']);
const {company_type} = toRefs<any>(proxy?.useDict("company_type"));
const {custom_type} = toRefs<any>(proxy?.useDict("custom_type"));
const loading = ref(false);
const customerForm = ref<Record<string, any>>({});
const entryList = ref<Record<string, any>[]>([]);
const searchValue = ref('');
const initForm = () => {
  return {
    belongOrg: null,
    brandInfoVoList: [],
    brandInfoBoList: [],
    companyType: "",
    contentVoList: [],
    customAreaVo: {
      province: '',
      city: '',
      county: ''
    },
    customCategoryBo: {
      brandId: '',
      categoryOne: '',
      categoryTwo: '',
      mainPush: '',
      entityType: '',
      customId: ''
    },
    customType: "",
    econKind: null,
    enName: "",
    entType: null,
    id: "",
    isOnStock: "0",
    logo: "",
    no: "",
    originalNameVoList: [],
    revokeInfoVo: {
      cancelReason: '',
      cancelDate: '',
      revokeReason: '',
      revokeDat: ''
    },
    stockType: '',
    zhName: '',
    zhShortName: '',
    briefIntro: '',
    externalTrade: '',
    externalTradeRatio: '',
    customMade: '',
    area: '',
    serviceScope: '',
    filings: '',
    annualOutput: '',
    annualValue: '',
    researchStaffNum: '',
    filingsNum: '',
    cbeSynDate: '',
    qccSynDate: ''
  }
}

function back() {
  if (!route.query.id) {
    router.push({name: "customerInformation"});
  } else {
    emit("back");
  }
}

function cbeSync() {
  if (!searchValue.value) return proxy?.$modal.msgWarning("请输入企业名称");
  synCbeInfo(searchValue.value, customerForm.value.sourceId).then((res: any) => {
    if (+res.code === 200) {
      proxy?.$modal.msgSuccess("cbe同步成功");
      const data = res.data;
      customerForm.value.cbeSynDate = dayjs().format('YYYY-MM-DD HH:mm:ss');
      customerForm.value.customType = data?.customType || '2';
      if (data) {
        customerForm.value.zhName = data.zhName;
        customerForm.value.zhShortName = data.zhShortName;
        customerForm.value.enName = data.enName;
        customerForm.value.logo = data.logo;
        customerForm.value.companyType = data.companyType;
        customerForm.value.briefIntro = data.briefIntro;

        // 日化展商 专业展商
        if (['1', '2'].includes(data.companyType)) {
          // 品牌字段
          const brandInfoVoList = customerForm.value.brandInfoVoList;
          const sourceIds = brandInfoVoList.map((item: any) => item.sourceId);
          const brandInfoBoList = data.brandInfoVoList || [];
          const arr: Record<string, any>[] = []; // 新增品牌
          brandInfoBoList.forEach((item: any) => {
            if (!sourceIds.includes(item.sourceId)) {
              item.customCategoryBo = item.customCategoryVo || {};
              item.channelsInfoBo = item.channelsInfoVo || {};
              arr.push(item)
            } else {
              const part = brandInfoVoList.find((sItem: any) => sItem.sourceId === item.sourceId)
              arr.push({
                id: part.id,
                brandDetails: item.brandDetails,
                brandImage: item.brandImage,
                brandLogo: item.brandLogo,
                brandName: item.brandName,
                customCategoryBo: {
                  ...item.customCategoryVo,
                  id: part.customCategoryVo.id,
                },
                channelsInfoBo: {
                  ...item.channelsInfoVo,
                  id: part.channelsInfoVo.id,
                }

              })
            }
          })
          if (arr.length) {
            customerForm.value.brandInfoBoList = arr
          } else {
            delete customerForm.value.brandInfoBoList
          }

          const deleteSourceIds = brandInfoBoList.map((item: any) => item.sourceId);
          const deleteArr: Record<string, any>[] = []; // 删除品牌
          brandInfoVoList.forEach((item: any) => {
            if (!deleteSourceIds.includes(item.sourceId)) {
              item.customCategoryBo = item.customCategoryVo || {};
              item.channelsInfoBo = item.channelsInfoVo || {};
              deleteArr.push(item)
            }
          })
          if (deleteArr.length) {
            customerForm.value.delBrandInfoBoList = deleteArr
          } else {
            delete customerForm.value.delBrandInfoBoList
          }
        }

        if (data.companyType === '3') {
          customerForm.value.externalTrade = data.externalTrade;
          customerForm.value.externalTradeRatio = data.externalTradeRatio;
          customerForm.value.customMade = data.customMade;
          customerForm.value.area = data.area;
          customerForm.value.serviceScope = data.serviceScope;
          customerForm.value.filings = data.filings;
          customerForm.value.annualOutput = data.annualOutput;
          customerForm.value.annualValue = data.annualValue;
          customerForm.value.researchStaffNum = data.researchStaffNum;
          customerForm.value.filingsNum = data.filingsNum;
          customerForm.value.engineer = data.engineer;
          customerForm.value.patent = data.patent;
          customerForm.value.minOrder = data.minOrder;
          customerForm.value.modelNum = data.modelNum;
          customerForm.value.packDesigners = data.packDesigners;
          customerForm.value.materialProductNum = data.materialProductNum;

          const partnerVoList = customerForm.value.partnerVoList;
          const partnerSourceIds = partnerVoList.map((item: any) => item.sourceId);
          const partnerBoList = data.partnerVoList || [];
          const list: Record<string, any>[] = []; // 新增合作伙伴
          partnerBoList.forEach((item: any) => {
            if (!partnerSourceIds.includes(item.sourceId)) {
              list.push(item)
            } else {
              const part = partnerVoList.find((sItem: any) => sItem.sourceId === item.sourceId)
              list.push({
                ...item,
                id: part.id,
              })
            }
          })
          if (list.length) {
            customerForm.value.partnerBoList = list
          } else {
            delete customerForm.value.partnerBoList
          }

          const deletePartnerIds = partnerBoList.map((item: any) => item.sourceId);
          const deleteList: Record<string, any>[] = []; // 删除合作伙伴
          partnerVoList.forEach((item: any) => {
            if (!deletePartnerIds.includes(item.sourceId)) {
              deleteList.push(item)
            }
          })
          if (deleteList.length) {
            customerForm.value.delPartnerBoList = deleteList
          } else {
            delete customerForm.value.delPartnerBoList
          }
        }

        if (['3', '4', '5'].includes(data.companyType)) {
          if (!customerForm.value.customCategoryVo) {
            customerForm.value.customCategoryVo = {
              brandId: '',
              categoryOne: '',
              categoryTwo: '',
              mainPush: '',
              entityType: '',
              customId: '',
              id: ''
            }
          }
          if (!customerForm.value.id) {
            customerForm.value.customCategoryVo = data.customCategoryVo
          } else {
            customerForm.value.customCategoryVo.brandId = data.customCategoryVo.brandId || ''
            customerForm.value.customCategoryVo.categoryOne = data.customCategoryVo.categoryOne || ''
            customerForm.value.customCategoryVo.categoryTwo = data.customCategoryVo.categoryTwo || ''
            customerForm.value.customCategoryVo.mainPush = data.customCategoryVo.mainPush || ''
            customerForm.value.customCategoryVo.entityType = data.customCategoryVo.entityType || ''
            customerForm.value.customCategoryVo.customId = data.customCategoryVo.customId || ''
          }
          customerForm.value.customCategoryBo = customerForm.value.customCategoryVo
        }
      }
    }
  })
}

function searchCustom() {
  if (!searchValue.value) return proxy?.$modal.msgWarning("请输入企业名称");
  queryQccInfo(searchValue.value).then((res) => {
    if (+res.code === 200) {
      proxy?.$modal.msgSuccess("企查查同步成功");
      customerForm.value.qccSynDate = dayjs().format('YYYY-MM-DD HH:mm:ss');

      const data = res.data;
      if(data.logo) customerForm.value.logo = data.logo;
      customerForm.value.no = data.no;
      customerForm.value.belongOrg = data.belongOrg;
      customerForm.value.operName = data.operName;
      customerForm.value.startDate = data.startDate;
      customerForm.value.endDate = data.endDate;
      customerForm.value.status = data.status;
      customerForm.value.province = data.province;
      customerForm.value.updatedDate = data.updatedDate;
      customerForm.value.updateTime = data.updateTime;
      customerForm.value.creditCode = data.creditCode;
      customerForm.value.registCapi = data.registCapi;
      customerForm.value.econKind = data.econKind;
      customerForm.value.address = data.address;
      customerForm.value.scope = data.scope;
      customerForm.value.termStart = data.termStart;
      customerForm.value.termEnd = data.termEnd;
      customerForm.value.checkDate = data.checkDate;
      customerForm.value.stockNumber = data.stockNumber;
      customerForm.value.recCap = data.recCap;
      customerForm.value.areaCode = data.areaCode;
      customerForm.value.isOnStock = data.isOnStock;
      customerForm.value.stockType = data.stockType;
      customerForm.value.entType = data.entType;

      if (!customerForm.value.customAreaVo) {
        customerForm.value.customAreaVo = {
          city: '',
          county: '',
          customId: '',
          province: '',
          id: ''
        }
      }
      if (!customerForm.value.revokeInfoVo) {
        customerForm.value.revokeInfoVo = {
          cancelDate: '',
          cancelReason: '',
          revokeDate: '',
          revokeReason: '',
          id: ''
        }
      }
      if (!customerForm.value.id) {
        customerForm.value.customAreaVo = data.customAreaVo;
        customerForm.value.revokeInfoVo = data.revokeInfoVo;
      } else {
        customerForm.value.customAreaVo.city = data.customAreaVo?.city;
        customerForm.value.customAreaVo.county = data.customAreaVo?.county;
        customerForm.value.customAreaVo.customId = data.customAreaVo?.customId;
        customerForm.value.customAreaVo.province = data.customAreaVo?.province;
        customerForm.value.customAreaBo = customerForm.value.customAreaVo;

        customerForm.value.revokeInfoVo.cancelDate = data.revokeInfoVo?.cancelDate;
        customerForm.value.revokeInfoVo.cancelReason = data.revokeInfoVo?.cancelReason;
        customerForm.value.revokeInfoVo.revokeDate = data.revokeInfoVo?.revokeDate;
        customerForm.value.revokeInfoVo.revokeReason = data.revokeInfoVo?.revokeReason;
        customerForm.value.revokeInfoBo = customerForm.value.revokeInfoVo;
      }

      const originalNameVoList = customerForm.value.originalNameVoList;
      const names = originalNameVoList.map((item: any) => item.name);
      const originalNameBoList = data.originalNameVoList || [];
      const arr: Record<string, any>[] = [];
      originalNameBoList.forEach((item: any) => {
        if (!names.includes(item.name)) {
          arr.push(item)
        } else {
          const part = originalNameVoList.find((sItem: any) => sItem.name === item.name)
          arr.push({
            ...item,
            id: part.id
          })
        }
      })
      if (arr.length) {
        customerForm.value.originalNameBoList = arr
      } else {
        delete customerForm.value.originalNameBoList
      }

      const deleteNames = originalNameBoList.map((item: any) => item.name);
      const deleteList: Record<string, any>[] = [];
      originalNameVoList.forEach((item: any) => {
        if (!deleteNames.includes(item.name)) {
          deleteList.push(item)
        }
      })
      if (deleteList.length) {
        customerForm.value.delOriginalNameBoList = deleteList
      } else {
        delete customerForm.value.delOriginalNameBoList
      }
    }
  });
}

function submitInfo() {
  if (loading.value) return;
  // 词条新增
  customerForm.value.contentBoList = [];
  entryList.value.forEach((item: any) => {
    const content = item.entryType === '3' ? item.content.join(',') : item.content;
    if (content) {
      const part = customerForm.value.contentVoList.find((sItem: any) => sItem?.entryId === item.id)
      customerForm.value.contentBoList.push({
        id: part?.id,
        entryId: item.id,
        content
      })
    }
  })
  console.log('667', customerForm.value)
  loading.value = true;
  if (customerForm.value.id) {
    updateCustom(customerForm.value).then((res) => {
      if (+res.code === 200) {
        proxy?.$modal.msgSuccess("修改成功");
        emit('update')
      }
    }).finally(() => loading.value = false);
  } else {
    saveCustom(customerForm.value).then((res) => {
      if (+res.code === 200) {
        proxy?.$modal.msgSuccess("保存成功");
        if (route.query.id) {
          emit('update')
        } else {
          router.push({name: "customerInformation"});
        }
      }
    }).finally(() => loading.value = false);
  }
}

function getCustomDetail() {
  customerForm.value = props.detail?.id ? props.detail : initForm();
  customerForm.value.customType = props.detail?.id ? (props.detail?.customType || '2') : '';
  customerForm.value.contentVoList = props.detail.contentVoList || [];
  customerForm.value.brandInfoVoList = props.detail.brandInfoVoList || [];
  customerForm.value.partnerVoList = props.detail.partnerVoList || [];
  customerForm.value.originalNameVoList = props.detail.originalNameVoList || [];
  searchValue.value = customerForm.value.zhName;
}

loading.value = true;
entryGetList().then((res) => {
  entryList.value = res.data || [];
  entryList.value.forEach((item) => {
    item.content = '';
    if (item.entryType === '3') item.content = [];
  })
}).finally(() => loading.value = false)

// 词条信息回显
watch([() => entryList.value, () => customerForm.value.contentVoList], () => {
  entryList.value.forEach((item: any) => {
    if (Array.isArray(customerForm.value.contentVoList)) {
     if (customerForm.value.contentVoList.length) {
       customerForm.value.contentVoList.forEach((sItem: any) => {
         if (sItem && sItem.entryId === item.id) {
           item.content = sItem.content;
           if (item.entryType === '3') item.content = sItem && sItem.content.split(',');
         }
       })
     } else {
       entryList.value.forEach((item) => {
         item.content = '';
         if (item.entryType === '3') item.content = [];
       })
     }
    }
  })
})

onMounted(() => {
  getCustomDetail();
});


defineComponent({name: "CustomerAddAndEdit"});
</script>

<style scoped lang="scss">
.add-edit-box {
  //width: 100%;
  margin-top: 40px;

  .title-box {
    position: relative;
  }

  .info-box {
    position: relative;
  }

  .part-title {
    margin: 10px 0 20px;
  }

  .add-btn,
  .reduce-btn {
    position: absolute;
    top: 8px;
    right: -40px;
    width: 24px;
    height: 24px;
    cursor: pointer;
  }

  .add-btn {
    background: url('@/assets/add.png');
  }

  .reduce-btn {
    background: url('@/assets/reduce.png');
  }
}

.operate-btn {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 80px;
  padding-right: 210px;
  display: flex;
  justify-content: end;
  align-items: center;
  background-color: #fff;
  box-shadow: 0 2px 10px 0 rgba(0,0,0,0.1);
  z-index: 99;

  div {
    width: 140px;
    height: 50px;
    margin-left: 30px;
    text-align: center;
    font-size: 16px;
    color: #FF4350;
    line-height: 48px;
    border-radius: 10px;
    border: 1px solid #FF4350;
    cursor: pointer;
  }

  .submit {
    color: #fff;
    border: none;
    background: linear-gradient(296deg, #FF4350 0%, #FF4553 35%, #FFADB3 100%);
  }
}

.search-box {
  width: 100%;
  margin: 10px 0;
}
</style>
